package com.example.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.order.Bean.Order;
import com.example.order.feign.ProductFeignClient;
import com.example.order.service.OrderService;

import com.example.product.Bean.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder",blockHandler = "createOrderFallBack")
    @Override
    public Order createOrder(Long productId, Long userId) {

        // 使用feign完成远程调用
        Product product = productFeignClient.getProductById(productId, "123");
        Order order = new Order();
        order.setId(1L);
        // 总金额计算
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("张三");
        order.setAddress("北京");
        // 商品列表远程查询
        order.setProductList(Arrays.asList(product));
        return order;
    }

    // 兜底回调
    public Order createOrderFallBack(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(BigDecimal.ZERO);
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("未知信息:" + e.getClass());
        return order;
    }

    private Product getProductFromRemote(Long productId) {
        return null;
    }
}
